package com.zzyl.job;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class AlertJob {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private AlertRuleService alertRuleService;

    /**
     * 设备上报数据报警规则过滤
     * 周期：每分钟执行一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void deviceDataAlertFilter() {
        //查询所有报警规则，如果为空，程序结束
        List<AlertRule> allAlertRules = alertRuleMapper.selectByFunctionId(null, null, null);
  log.info("查询所有报警：{}", allAlertRules);
        if (CollUtil.isEmpty(allAlertRules)) {
            return;
        }

//2.查询所有设备最新上报数据，如果为空，程序结束
        List<Object> jsonStrList = redisTemplate.opsForHash().
                values(CacheConstants.DEVICE_LASTDATA_CACHE_KEY);

        if (CollUtil.isEmpty(jsonStrList)) {
            return;
        }
        //3 设备上报数据不为空，提取设备上报数据为list
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();


        jsonStrList.forEach(json -> deviceDataVoList.addAll(
                JSONUtil.toList(json.toString(), DeviceDataVo.class)
        ));
//4、对每一条设备上报的数据进行报警规则校验

        deviceDataVoList.forEach(d -> alertRuleService.alertFilter(d));

    }


}





